<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Dianzan;
use app\validate\Image ;
use app\model\Article as ArticleModel;
use app\model\Images;
use app\model\Questions;
use think\exception\ErrorException;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;
use think\Request;
use app\model\Section as SectionModel;

class Blog extends Base
{
    /**
     * 显示资源列表
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function index(Request $request)
    {
//        $sections=Db::name('section')->order('sClickNum','desc')->field('sId,sName')
//            ->select()->toArray();
        $data=$request->param();
        $sec=$data['section']?$data['section']:1;
        $article=Db::name('article')->where('sectionId',$sec)
            ->order(['aHot'=>'desc','aTime'=>'desc'])//排序
            ->page($this->page,$this->page_size)//分页
            ->select()->toArray();
//        $result=array_merge($sections,$article);
        if($article){
            return $this->createApi($article,'查询成功',200);
        }else{
            return $this->createApi([],'查询失败',204);
        }
    }

    public function total(){
        $sections=Db::name('section')->order('sClickNum','desc')->field('sId,sName')
            ->select()->toArray();
        return $this->createApi($sections,'success',200);
    }

    public function hotArticle(){

        $article=ArticleModel::where('aId',69)
            ->whereOr('aId',70)
            ->whereOr('aId',71)
            ->whereOr('aId',72)
            ->select();

        for( $i=0;$i<5;$i++) {
            $image=Images::where('b_id',$article[$i]['aId'])->field('img_add')->find()->toArray();
            $article[$i]['image']=$image;
        }
        return $this->createApi($article,'success',200);
    }

    /**
     * 显示创建资源表单页.
     *  @param  \think\Request  $request
     * @return \think\Response
     */
    public function create(Request  $request)
    {
        $data=$request->param();
        $files = request()->file('image');
        $section=SectionModel::where('sId',$data['section'])->find();
        $section->sTopicNum++;
        $section->save();//统计模块的文章数目
        $username=Session::get('username');
        if($data['title']==null||$data['content']==null){
            return $this->createApi([],'文章标题和内容不能为空',204);
        }
        $article=ArticleModel::create([
                'sectionId'=>$data['section'],
                'uName'=>$username,
                'aTitle'=>$data['title'],
                'aContent'=>$data['content']
            ]
        )->toArray();
        //创建文章内容
        //保存文章图片
        if($files){
            try {
                validate(Image::class)
                    ->check($files);
                $savename=[];
                foreach($files as $file) {
                    $save= \think\facade\Filesystem::disk('public')->putFile( 'blogs', $file);
                    $image=Images::create([
                        'is_blog'=>1,
                        'b_id'=>$article['id'],
                        'img_add'=>'storage/'.str_replace('\\','/',$save)
                    ]);
                    $savename[]=$save;
                }
                return $this->createApi(array_merge($savename,$article),'创建成功',200);
            } catch (\think\exception\ValidateException $e) {
                return $this->createApi([],$e->getMessage(),400);
            }
        }
        return $this->createApi($article,'创建成功',200);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $article=ArticleModel::where('aId',$id)->field('uName,aTitle,aTime,aContent,aHot')
            ->find()->toArray();
        $images=Images::where('b_id',$id)->field('img_add')->select()->toArray();
        $results=array_merge($images,$article);
        if($results){
            return $this->createApi($results,'查看成功',200);
        }else{
            return $this->createApi([],'查看失败',204);
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function setHot(Request $request)//点击的时间更新热度？
    {
        $data=$request->param();
        $username=Session::get('username');
        $article=ArticleModel::where('aId',$data['id'])->find();
        $article->aHot++;
        $good=Dianzan::create([
            'artId'=>$data['id'],
            'art_author'=>$article->uName,
            'artTitle'=>$article->aTitle,
            'zanUser'=>$username
        ]);
        if($article->save()&&$good){
            return $this->createApi($article,'更新成功',200);
        }else{
            return $this->createApi([],'更新失败',204);
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request,$id)//作者更新文章
    {
        if(!Validate::isInteger($id)){
            return $this->createApi([], '数据不合法', 400);
        }
        $data=$request->param();
        $files=request()->file('image');
        $username=Session::get('username');
        $article=ArticleModel::where('aId',$id)->find();
        if($username==$article->uName){
            @$article->aTitle=$data['title'];
            @$article->aContent=$data['content'];
            $article->aTime=date("Y-m-d H:i:s",time());
            $article->save();
            if($files){
                try {
                    validate(Image::class)
                        ->check($files);
                    $savename=[];
                    foreach($files as $file) {
                        $save= \think\facade\Filesystem::disk('public')->putFile( 'blogs', $file);
                        $image=Images::create([
                            'is_blog'=>1,
                            'b_id'=>$id,
                            'img_add'=>'storage/'.str_replace('\\','/',$save)
                        ]);
                        $savename[]=$save;
                    }
                    return $this->createApi(array_merge($savename,$article),'更新成功',200);
                } catch (\think\exception\ValidateException $e) {
                    return $this->createApi([],$e->getMessage(),400);
                }
            }
            return $this->createApi($article,'更新成功',200);
        }else{
            return $this->createApi([],'你无权编辑',204);
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $username=Session::get('username');
        if(!Validate::isInteger($id)){
            return $this->createApi([], '数据不合法', 400);
        }
        try{
            $article=ArticleModel::where('aId',$id)->find();
            if($article->uName!=$username){
                return $this->createApi([], '你无法删除', 400);
            }
            $article->delete();
            return $this->createApi([], '删除成功', 200);
        }catch(\Error $e){
            return $this->createApi([], '无法删除', 400);
        }
    }

    public function deleteIamges(Request $request){
        $data=$request->param();
        $username=Session::get('username');
        $image=Images::where('img_id',$data['img_id'])->find();
        if($image->article->uName!=$username){
            return $this->createApi([], '你无法删除', 400);
        }
        if(unlink('../public/'.$image->img_add)&&$image->delete()){
            return $this->createApi([], '删除成功', 200);
        }else{
            return $this->createApi([], '删除失败', 204);
        }
    }
    public function search(Request $request){
        $data=$request->param();
        $articles=ArticleModel::where('aTitle','like','%'.$data['filename'].'%')
            ->order(['aHot'=>'desc','aTime'=>'desc'])//排序
            ->page($this->page,$this->page_size)
            ->select()->toArray();
        if($articles){
            return $this->createApi($articles, '查询成功', 200);
        }else{
            return $this->createApi([], '无结果', 204);
        }
    }
}
